import { Controller, Get, Post, Param, Query, Body, BadRequestException } from '@nestjs/common';
import { ChatroomService } from './chatroom.service';
import { RequireLogin, UserInfo } from "src/custom.decorator";


// 由于每一个接口都需要登录后才有权限，我们直接在controller类上加，不再单独一个个的给controller类中的每个handler上加了
@Controller('chatroom')
@RequireLogin()
export class ChatroomController {
  constructor(private readonly chatroomService: ChatroomService) { }

  /* 创建聊天室（包含一对一聊天室和群聊） */
  @Get('create-one2one')
  async onToOne(@Query('friendId') friendId: number, @UserInfo('userId') userId: number) {
    if (!friendId) throw new BadRequestException('建立聊天的好友id不能为空');
    return this.chatroomService.createOneToOneChatroom(friendId, userId);
  }

  @Get('create-group')
  async group(@Query('name') name: string, @UserInfo('userId') userId: number) {
    return this.chatroomService.createGroupChatroom(name, userId);
  }

  /* 查询当前登录用户所有的群聊 */
  @Get('list')
  async list(@UserInfo('userId') userId: number, @Query('name') name: string) {
    if (!userId) throw new BadRequestException('userId 不能为空');
    return this.chatroomService.list(userId, name);
  }

  /* 查询聊天室中所有的用户 */
  @Get('members')
  async members(@Query('chatroomId') chatroomId: number) {
    if (!chatroomId) throw new BadRequestException('chatroomId 不能为空');
    return this.chatroomService.members(chatroomId);
  }

  /* 查询单个聊天室信息 */
  @Get('info/:id')
  async info(@Param('id') id: number) {
    if (!id) throw new BadRequestException('id不能为空');
    return this.chatroomService.info(id);
  }

  /* 加入群聊&退出群聊 */
  @Get('join/:id')
  async join(@Param('id') id: number, @Query('joinUsername') joinUsername: string) {
    if (!id) throw new BadRequestException('id不能为空');
    if (!joinUsername) throw new BadRequestException('joinUsername不能为空');

    return this.chatroomService.join(id, joinUsername);
  }

  @Get('quit/:id')
  async quit(@Param('id') id: number, @Query('quitUserId') quitUserId: number) {
    if (!id) {
      throw new BadRequestException('id 不能为空')
    }
    if (!quitUserId) {
      throw new BadRequestException('quitUserId 不能为空')
    }

    return this.chatroomService.quit(id, quitUserId);
  }

  @Get('findChatroom')
  async findChatroom(@Query('userId1') userId1: string, @Query('userId2') userId2: string) {
    if (!userId1 || !userId2) throw new BadRequestException('用户id不能为空');

    return this.chatroomService.queryOneToOneChatroom(+userId1, +userId2);
  }
}
